package com.rds.benchmark.operator;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.commands.JedisCommands;

import java.io.IOException;

public class ZsetOperator extends TypeOperatorBase {

    private Object conn;

    private String key;

    private final static int SUBCONTENTS = 1000;

    private String[] mkey;

    @Override
    public void init(Object conn, String key, int idx,String mode) {
        this.conn = conn;
        this.key = key;

        this.mkey = new String[SUBCONTENTS];
        for (int i = 0; i < SUBCONTENTS; i++) {
            mkey[i] = "thread-123456789012345678901234567890123456789012345678901234567890-" + idx + "--" + i;
        }
    }

    @Override
    public Long clear() {
        return ((JedisCommands) conn).del(key);
    }

    @Override
    public void operate() throws IOException {
        if(conn instanceof Jedis){
            Jedis jedis = (Jedis) conn;
            for (int i = 0; i < SUBCONTENTS; ++i) {
                jedis.zadd(key, i, mkey[i]);
                times ++;
            }
            for (int i = 0; i < SUBCONTENTS; ++i) {
                jedis.zrem(key, mkey[i]);
                times ++;
            }
        }else if(conn instanceof JedisCluster){
            JedisCluster jedisCluster = (JedisCluster) conn;
            for (int i = 0; i < SUBCONTENTS; ++i) {
                jedisCluster.zadd(key, i, mkey[i]);
                times ++;
            }
            for (int i = 0; i < SUBCONTENTS; ++i) {
                jedisCluster.zrem(key, mkey[i]);
                times ++;
            }
        }
    }

}
